import utils, { NameSpace } from 'utils';
import exceed from 'utils/apimap';
import { navigate } from 'utils/router';
import { Message } from '@teamix/ui';
import intl from '../../../../../../../../../locale';

const ns = NameSpace('GROUP_SETTINGS');
const { pathResource, organization } = window.FORCE;
// let checkTransferTimeout;
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RESET_DATA = ns('RESET_DATA');
export const RECEIVE_GROUP_SETTING = ns('RECEIVE_GROUP_SETTING');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function resetData() {
  return (dispatch) => {
    dispatch({
      type: RESET_DATA,
    });
  };
}

// 获取组基本信息
export function getGroupDetailInfo() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'groups.details',
        params: {
          id: pathResource.id,
        },
      })
      .then((res) => {
        res.visibility_level = utils.processVisibilityLevel(Number(res.visibility_level));
        updateData({
          groupInfo: utils.processVisibilityLevel(res),
        })(dispatch);
      });
  };
}

export function saveGeneral(data, callback) {
  return () => {
    callback(true);
    exceed
      .fetch({
        api: 'groups.update',
        params: {
          id: pathResource.id,
        },

        data,
      })
      .then(() => {
        callback(false);
        Message.success({
          title: intl.get({
            id: 'code-assets.settings.actions.SavedSuccessfully',
            defaultMessage: '保存成功',
          }),
        });

        window.location.reload();
      })
      .fail(() => {
        callback(false);
      });
  };
}

// 查当前用户有权限创建代码组的所有组（集团：后端携带个人namespace返回）
export function searchNamespaces(search, callback) {
  return () => {
    exceed
      .forceFetch({
        api: 'groups.list.all.authorized',
        data: {
          search,
          namespace_id: organization.namespace_id,
        },
      })
      .then((result) => {
        callback(result);
      });
  };
}

export function rename(data, callback) {
  return () => {
    callback({
      submitting: true,
      visible: true,
    });

    exceed
      .forceFetch({
        api: 'groups.update',
        params: {
          id: pathResource.id,
        },

        data,
      })
      .then(() => {
        const prefix = window.location.pathname.match(/(.*)\/.*\/settings/)[1];
        Message.success({
          title: intl.get({
            id: 'code-assets.settings.actions.TheGroupPathIsUpdated',
            defaultMessage: '组路径更新成功',
          }),
        });

        callback({
          submitting: false,
          visible: false,
        });
        navigate(`${window.location.origin}${prefix}/${data.path}/settings`, { state: { forceUpdate: true } });
      });
  };
}

// 查询企业设置
export function getGroupSettingData() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'organization.group.setting.get',
        params: {
          org_id: organization.id,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_GROUP_SETTING,
          data: result,
        });
      });
  };
}

export function transfer({ target_id, target_path }, callback) {
  const suffix = pathResource.fullPath.split('/')[pathResource.fullPath.split('/').length - 1];
  return () => {
    // callback({
    //   submitting: true,
    //   isModalOpen: true,
    // });
    exceed
      .forceFetch({
        api: 'groups.transfer',
        params: {
          source_id: pathResource.id,
          target_id,
        },
      })
      .then((result) => {
        if (result.result === true) {
          Message.success({
            title: intl.get({
              id: 'code-assets.settings.actions.TransferSucceeded',
              defaultMessage: '转移成功',
            }),
          });
          navigate(`/${target_path}/${suffix}/settings`, { state: { forceUpdate: true } });
        } else {
          Message.error({
            title: intl.get({
              id: 'code-assets.settings.actions.TransferFailed',
              defaultMessage: '转移失败',
            }),
          });
        }
        callback && callback();
      });
  };
}
